import React from 'react';
import {Table, Input, Switch, Popconfirm, Form, Card, Select, message, Tooltip, Button, Icon} from 'antd';
import SearchForm from '../../components/AutoForm/SearchForm';
import {connect} from "dva";
const { Option } = Select;

const EditableContext = React.createContext();

@connect(({driver}) => ({
  requiredCols: driver.requiredCols
}))
class EditableCell extends React.Component {


  getInput = (dataIndex, record) => {
    switch (dataIndex) {
      case 'isLock':
        return <Select style={{width: 90}}>
          <Option value="0">否</Option>
          <Option value="1">是</Option>
        </Select>
      default:
        return <Input />
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0}}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue: record[dataIndex]+'',
            })(this.getInput(dataIndex, record))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({driver, loading}) => ({
  tableLoading: loading.effects['driver/page'],
  tableData: driver.pageList,
  pagination: driver.pagination,
  columns: driver.columns,
  searchFields: driver.searchFields,
  searchValues: driver.searchValues,
  editId: driver.editId,
  selectionIds: driver.selectionIds
}))
class EditableTable extends React.Component {

  componentDidMount() {
    this.handleSearch();
  }
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'driver/handleEdit',
      payload: ''
    })
  };

  save(form, id) {
    const { dispatch } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      dispatch({
        type: 'driver/save',
        payload: { ...row, id: id.id }
      }).then(() => {
        this.handleSearch()
      })
    });
  }

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'driver/handleEdit',
      payload: key
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'driver/handleSearchChange',
      payload: fields
    })
  }

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'driver/handleAdd'
    })
  }

  handleSearch = (flag) => {
    const {dispatch, pagination, searchValues} = this.props;
    let pageParam = {pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current }
    let searchParam = {};
    Object.keys(searchValues).map((key) => {
      searchParam[key] = searchValues[key]['value'];
    })
    const param = {
      ...searchParam,
      ...pageParam
    };
    dispatch({
      type: 'driver/page',
      payload: param
    })
  }

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'driver/handleSelection',
      payload: selectedRowKeys
    })
  }

  onDel = () => {
    const { dispatch, selectionIds } = this.props;
    if(!selectionIds.length){
      return message.error('请选择一行要删除的数据')
    }
    dispatch({
      type: 'driver/del',
      payload: selectionIds
    }).then(() => {
      this.handleSearch()
    })
  }


  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch
    } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });

    optColumns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <span>
              <EditableContext.Consumer>
                {form => (
                  <Tooltip placement="bottom" title="保存">
                    <Button size="small"  onClick={() => this.save(form, record)} icon="save"></Button>
                  </Tooltip>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确认取消?" cancelText="取消" okText="确定" onConfirm={() => this.cancel(record.id)}>
                <Tooltip placement="bottom" title="撤回">
                  <Button size="small" icon="rollback"></Button>
                </Tooltip>
              </Popconfirm>
            </span>
        ) : (
          <Tooltip placement="bottom" title="编辑">
            <Button disabled={editId !== '' } size="small" icon="edit" onClick={() => this.handleEdit(record.id)}></Button>
          </Tooltip>
        );
      }
    })

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map((key) => {
        searchParam[key] = searchValues[key]['value'];
      })
      dispatch({
        type: 'driver/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize
        }
      })
    }
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map((key) => {
        searchParam[key] = searchValues[key]['value'];
      })
      dispatch({
        type: 'driver/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size
        }
      })
    }

    const rowSelection = {
      type: "checkbox",
      onChange: this.onChange
    };

    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="司机信息->操作"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          isAdd={true}
          isDel={true}
          onAdd={this.handleAdd}
          onSubmit={() => {this.handleSearch('btn')}}
          onDel={this.onDel}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            rowKey="id"
            loading={tableLoading}
            dataSource={tableData}
            columns={optColumns}
            rowSelection={rowSelection}
            rowClassName="editable-row"
            scroll={{x: 'max-content'}}
            size="small"
            pagination={pagination}
          />
        </EditableContext.Provider>
      </Card>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
